#ifndef BOOTLOADER_ABOOTLOADER_H
#define BOOTLOADER_ABOOTLOADER_H

#include "Arduino.h"

#ifdef STM32F1

#include "stm32f1xx.h"
#include "EEPROM.h"
#endif

#define APP_START_ADDRESS 0x08004000

#define ACK     0X55
#define NACK    0XAA

#define WRITE  0x01
#define RUN 0x02

#include "constdef.h"
class Bootloader {

public:
    HardwareSerial *serial;
    uint32_t app_addr;

    Bootloader(HardwareSerial *serial, uint32_t app_addr);

    bool unlock_flash(void);

    bool lock_flash(void);

    bool erase_flash(uint32_t start, uint32_t end);

    bool write_flash(uint32_t addr, uint16_t *data, uint32_t len);

    bool read_flash(uint32_t addr, uint16_t *data, uint32_t len);

    bool jump_to_app(void);

    bool check_update_flag(void);

    bool poll(void);

protected:
    uint16_t fl_buffer[FLASH_PAGE_SIZE];
    uint8_t rx_buffer[40];
    uint16_t index = 0;
    uint16_t write_buffer[1024];
    uint32_t write_addr;
    uint16_t crc16(uint8_t *data, uint8_t len);
    bool fill_buffer(uint8_t *data,uint32_t addr);
};


#endif //BOOTLOADER_ABOOTLOADER_H
